<template>
  <div class="lab-list-root">
    <lark-drawer border title="实验室列表" title-height="40px" width="420px" height="max-content">


      <div class="l-l-body">


        <div class="l-l-body-head">

          <div v-if="tableData && Array.isArray(tableData) && tableData.length===1 && total === 1"
               class="h-container">
            <el-button size="mini" icon="el-icon-plus" class="l-l-body-head__add"
                       @click="addLabBtn({type:TYPES.ADD})" round>
              新增
            </el-button>
            <el-button size="mini" icon="el-icon-plus" class="l-l-body-head__add"
                       @click="addLabBtn({type:TYPES.EDIT})" round>
              修改
            </el-button>
            <el-button size="mini" icon="el-icon-plus" class="l-l-body-head__add"
                       @click="manager({type:TYPES.PRO})" round>
              专家
            </el-button>
            <el-button size="mini" icon="el-icon-plus" class="l-l-body-head__add"
                       @click="manager({type:TYPES.CER})" round>
              资质
            </el-button>
          </div>

          <div v-if="tableData && Array.isArray(tableData) && tableData.length>1 && total > 1"
               class="h-container">
            <el-input class="l-l-body-head__search" v-model="searchParams.name" placeholder="输入实验室名称进行搜索">
              <el-button slot="append" icon="el-icon-search" @click="getLabDataList"></el-button>
            </el-input>
            <el-button icon="el-icon-plus" class="l-l-body-head__add" @click="addLabBtn({type:TYPES.ADD})" round>
              新增
            </el-button>
          </div>

        </div>

        <div class="l-l-list" id="l-l-list" v-loading="loading">


          <div v-if="tableData && Array.isArray(tableData) && tableData.length===1 && total === 1"
               class="dan-z t-container">
            <div class="t-row" v-for="(item, index) in valueTableData"
                 :key="`${item.label}_${item.value}_${index}`"
                 @click="submit">
              <div class="t-column t-c-label">{{item.label}}:</div>
              <div class="t-column t-c-value">{{item.value}}</div>
            </div>
          </div>

          <line-table @rowClick="submit" v-if="tableData && Array.isArray(tableData) && tableData.length>1 && total > 1" :table-data="tableData"
                      :table-header="tableHeaders">
            <template v-slot:operation="{row}">
              <el-dropdown>
                <div class="l-l-list-row-operation-btn"
                     style="width:15px;margin-left: 10px">
                  <i class="fa fa-ellipsis-v" aria-hidden="true"></i>
                </div>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item icon="el-icon-delete" @click.native="deleteBtn(row)">
                    删除
                  </el-dropdown-item>
                  <el-dropdown-item icon="el-icon-edit"
                                    @click.native="addLabBtn({type:TYPES.EDIT, id:row.id})">
                    修改
                  </el-dropdown-item>
                  <el-dropdown-item icon="el-icon-edit"
                                    @click.native="manager({type:TYPES.PRO, id:row.id})">
                    专家
                  </el-dropdown-item>
                  <el-dropdown-item icon="el-icon-edit"
                                    @click.native="manager({type:TYPES.CER, id:row.id})">
                    资质
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </line-table>


        </div>
        <div class="l-l-pagination">

          <el-pagination
            v-if="total>1"
            small
            layout="prev, pager, next"
            :total="total"
            :current-page.sync="searchParams.pageNum"
            :page-size="searchParams.pageSize"
            @current-change="getLabDataList"
          >
          </el-pagination>

        </div>
      </div>
    </lark-drawer>


    <lark-card border :x="500" body-height="400px" :body-width="'500px'" v-if="open" :hidden="!open"
               @closeAction="open = !open"
               :card-title="openType === TYPES.ADD ? '新增实验室' : '修改实验室'" draggable
               :radius="false">
      <el-scrollbar>
        <div class="edit-lab-body" style="padding: 10px 5px">
          <el-form ref="edit-lab-form" :model="editForm" label-width="100px" :rules="rules" v-if="">

            <el-form-item label="实验室名称" prop="name">
              <el-input v-model="editForm.name"></el-input>
            </el-form-item>

            <el-form-item label="实验室面积" prop="area">
              <el-input v-model.number="editForm.area"></el-input>
            </el-form-item>

            <el-form-item label="实验室类型" prop="type">
              <el-select v-model="editForm.type" placeholder="请选择任务组名" clearable size="small">
                <el-option
                  v-for="dict in typeList"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="实验室位置" prop="position">
              <el-input v-model.number="editForm.position"></el-input>
            </el-form-item>


            <el-form-item label="实验室点位">
              <el-col :span="6">
                <el-input v-model.number="editForm.x" v-if="graphic != null"/>
              </el-col>
              <el-col style="text-align: center" :span="2">-</el-col>
              <el-col :span="6">
                <el-input v-model.number="editForm.y" v-if="graphic != null"/>
              </el-col>
              <el-col :span="4" style="margin-left: 10px">
                <el-button size="mini" @click="drawArea">绘制区域</el-button>
              </el-col>
            </el-form-item>

            <el-form-item label="实验室描述" prop="remark">
              <el-input v-model="editForm.remark"></el-input>
            </el-form-item>

          </el-form>

          <div class="edit-lab-submit">
            <el-button @click="saveBtn">保存</el-button>
          </div>

        </div>
      </el-scrollbar>
    </lark-card>

  </div>
</template>

<script>
  import { reactive, toRefs, onMounted, ref, computed, watch } from '@vue/composition-api'
  import { Message, MessageBox } from 'element-ui'
  import store from '@/store'
  import router from '@/router'
  import { addLab, deleteLab, editLab, labList } from '@/api/industry/lab'
  import { getDicts } from '@/api/system/dict/data'
  import { draw, clearDrawGeometry, getGraphic } from 'lark-map'
  import lineTable from '@/components/ServiceComponents/lineTable'

  export default {
    name: 'labList',
    props: {
      labId: {
        type: [Number, String],
        default: ''
      },
      queryType: {
        type: [Number, String],
        default: null
      },
      pageNum: {
        type: [Number, String],
        default: null
      },
      pageSize: {
        type: [Number, String],
        default: null
      },
      showType: {
        type: [Number, String],
        default: null
      },
      proId: {
        type: [Number, String],
        default: null
      },
      view: {
        type: Object,
        default: () => null
      }
    },
    components: {
      lineTable
    },
    setup(props, content) {

      let {} = props

      const TYPES = {
        ADD: 'add',
        EDIT: 'edit',
        PRO: '/pro',
        CER: '/cer'
      }
      const tableHeaders = [
        { name: '名称', prop: 'name', width: '100px' },
        { name: '面积', prop: 'area', width: '80px' },
        { name: '位置', prop: 'position', width: '90px' },
        { name: '描述', prop: 'remark', width: '50px' },
        { name: '操作', prop: 'operation', type: 'slot' }
      ]
      const data = reactive({
        TYPES,
        tableHeaders,
        typeList: [],
        searchParams: {
          name: null,
          pageNum: 1,
          pageSize: 5,
          status: '0'
        },
        tableHeader: [
          {
            label: '名称',
            value: 'name'
          },
          {
            label: '面积',
            value: 'area'
          },
          {
            label: '位置',
            value: 'position'
          },
          {
            label: '描述',
            value: 'remark'
          }
        ],
        tableData: [],
        loading: false,
        open: false,
        openType: '',
        total: 0,
        editForm: {
          name: null,
          area: null,
          position: null,
          x: null,
          y: null,
          remark: null,
          type: null
        },
        rules: {
          name: [
            { required: true, message: '实验室名称不能为空', trigger: 'blur' }
          ],
          area: [
            { required: true, message: '实验室面积不能为空', trigger: 'blur' },
            { type: 'number', message: '实验室面积必须为数字值' }
          ]
        },
        graphic: null

      })

      let valueTableData = computed(() => {
        let { tableData, tableHeader } = data

        let res = []

        if (!tableData?.length) return res

        tableHeader.forEach(headItem => {
          let { label, value } = headItem
          res.push({ label, value: tableData[0][value] })
        })

        return res
      })

      const reset = () => {
        data.editForm = {
          name: null,
          area: null,
          position: null,
          x: null,
          y: null,
          remark: null,
          type: null
        }
      }

      const submit = ({ id: labId }) => {
        if (!data?.tableData?.length) return
        let bufferLabId = data.tableData[0].id
        content.emit('submit', { labId: labId || bufferLabId, type: 1 })
      }

      const getLabDataList = () => {
        let { searchParams } = data
        data.loading = true
        labList(searchParams).then(res => {
          data.tableData = res.rows
          data.loading = false
          data.total = res.total
        })
      }

      const addLabBtn = ({ type, id }) => {
        data.openType = type
        data.open = true
        if (type === data.TYPES.EDIT) {
          let { name, area, position, remark, id: labId } = id ? data.tableData.find(item => item.id === id) : data.tableData[0]
          data.editForm = { name, area, position, remark, id: labId }
        }
      }

      const manager = ({ type, id }) => {
        let { id: bufferLabId } = id ? data.tableData.find(item => item.id === id) : data.tableData[0]
        let { labId, pageNum, pageSize, queryType, proId, showType } = props
        switch (type) {
          case data.TYPES.PRO:
            router.push({
              path: data.TYPES.PRO,
              query: { id: bufferLabId, labId, pageNum, pageSize, queryType, proId, showType }
            })
            break
          case data.TYPES.CER:
            router.push({
              path: data.TYPES.CER,
              query: { id: bufferLabId, labId, pageNum, pageSize, queryType, proId, showType }
            })
            break
        }
      }

      const deleteBtn = ({ id }) => {
        if (!id || id === '') return

        MessageBox.confirm('此操作将删除该实验室, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteLab(id).then(res => {
            Message.success('删除成功')
            getLabDataList()
          })
        })
      }

      const drawArea = async() => {
        let { view } = props
        data.graphic = await draw({ type: 'point', view })
        let { geometry: { x, y } } = data.graphic
        data.editForm.x = x
        data.editForm.y = y
      }

      const saveBtn = () => {
        content.refs['edit-lab-form'].validate(async valid => {
          if (!valid) return
          let { editForm } = data

          if (editForm?.id) {
            await editLab(editForm)
            Message.success('修改成功')
          } else {
            await addLab(editForm)
            Message.success('添加成功')
          }

          getLabDataList()
          data.open = false
          reset()
        })
      }

      const getTypeList = () => {
        getDicts('sys_lab_type').then(res => {
          data.typeList = res.data
        })
      }

      watch(() => data.open, val => {
        if (!val) {
          let { view } = props
          clearDrawGeometry({ view })
          data.graphic = null
        }
      })

      watch(() => data.editForm, val => {
        if (!data.graphic) return
        let { graphic: { geometry: { x, y, spatialReference }, symbol, attributes } } = data
        if (val.x === x && val.y === y) return

        data.graphic.geometry = getGraphic({
          attributes,
          symbol,
          point: [val.x, val.y],
          geometryType: 'point',
          spatialReference
        }).geometry

      }, { deep: true })

      getLabDataList()
      getTypeList()

      return {
        ...toRefs(data),
        valueTableData,
        submit,
        getLabDataList,
        addLabBtn,
        deleteBtn,
        drawArea,
        saveBtn,
        manager
      }
    }
  }
</script>

<style lang="scss">
  $list-row-height: 36px;
  $full: 100%;
  .lab-list-root {
    position: absolute;
    top: 120px;

    .lark-drawer-root {
      position: relative;
      top: 5%;


      .l-l-body {
        position: relative;
        padding: 10px 10px 0 10px;
        height: 42vh;

        .l-l-pagination {
          height: 35px;
        }

        .l-l-list {
          height: calc(42vh - 68px - 35px);
          overflow: hidden;

          .t-container {
            width: 100%;
            font-size: 20px;

            &.dan-z {
              height: 20vh;
              display: flex;
              flex-direction: column;
              cursor: pointer;

              .t-row {
                flex: 1;
                display: flex;
                width: $full;
                flex-direction: row;

                .t-column {
                  display: flex;
                  flex-direction: column;
                  justify-content: center;


                  &.t-c-label {
                    flex-basis: 20%;
                    text-align: right;
                  }

                  &.t-c-value {
                    flex: 1;
                    text-align: left;
                    padding-left: 5px;
                  }
                }
              }
            }

            &.duo-z {
              height: 100%;

              .l-l-list-row {
                height: $list-row-height;
                line-height: $list-row-height;
                display: flex;
                flex-direction: row;
                border-bottom-style: dashed;
                border-bottom-width: 1px;
                justify-content: space-between;

                .l-l-list-row-item {
                  flex: 1;
                }
              }

              .h-h-container {
                height: calc(100% - 40px);
              }

              .el-scrollbar {
                .l-l-list-row {
                  .l-l-list-row-item {
                    cursor: pointer;
                    flex-basis: 25%;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                  }
                }
              }
            }
          }

        }

        .l-l-body-head {
          display: flex;
          flex-direction: row;

          .h-container {
            display: flex;
            flex-direction: row;

            .l-l-body-head__search {
            }

            .l-l-body-head__add {
              margin-left: 10px;
            }
          }
        }
      }

      .l-b-content {
        height: 10vh;
        display: flex;
        padding: 5%;
        flex-direction: row;
        justify-content: flex-end;
        align-content: flex-start;

        .el-button {
          height: 40px;
        }

      }
    }
  }

  .edit-lab-body {
    position: relative;
    height: 390px;

    .edit-lab-submit {
      position: absolute;
      right: 20px;
      bottom: 10px;
    }
  }
</style>
